<template>
    <div ref="canvas"></div>
</template>

<script setup lang="ts">
import { Chart, View } from '@antv/g2';
import { v4 } from 'uuid';
import { onMounted, onUnmounted, ref, shallowRef, watch } from 'vue';

type IDate = { name: string, count: number, color?: string }
const prop = defineProps<{ data: IDate[], height: number, color: string[] }>()
const tclass = v4()
const canvas = ref<HTMLDivElement>()
const chart = shallowRef<Chart>()


function rangedata(data: IDate[]): IDate[] {
    if (data.length < 10) return data
    let d: IDate[] = []
    for (let V in data) {
        const v = Number(V)
        if (v >= 10) {
            d[10] ? d[10].count + data[v].count : d[10] = { name: '其他', count: data[v].count, color: '#FFEBE5' }
        } else {
            d.push(data[v])
        }
    }
    return d
}


const _chart = shallowRef<View>()

watch(() => prop.data, () => {
    _chart.value?.changeData(rangedata(prop.data));

    _chart.value?.render();
})



onMounted(() => {
    let all = 0
    prop.data.forEach((a) => all = a.count + all)
    if (canvas.value) {
        chart.value = new Chart({
            container: canvas.value,
            autoFit: true,
            height: prop.height,
            width: 190
        })

        const color = ['l(315) 0:#0670F8 1:#34C7FC',
            'l(180) 0:#FCF100 1:#F5A300',
            'l(180) 0:#50FE83 1:#1CDD5E',
            'l(180) 0:#FE8B16 1:#F84228',
            'l(180) 0:#988FF9 1:#6A47C0',
            'l(180) 0:#FA76B7 1:#FB4099',

        ]
        chart.value?.theme({ "styleSheet": { "brandColor": "#014c63", paletteQualitative10: color, paletteQualitative20: prop.color } });
        chart.value?.interval()
            .position('count')
            .color('name', color)
            .label(false)
            .adjust('stack');
        chart.value.data(rangedata(prop.data));
        chart.value.coordinate('theta', {
            radius: 0.8,
            innerRadius: 0.7,
        });
        
        // chart.value.scale('name', false);
        chart.value.tooltip({
            showTitle: false,
            showMarkers: false,
        });
        _chart.value = chart.value.interaction(tclass);
        chart.value.legend(false)
        chart.value.render();
    }

})

onUnmounted(() => {
    if (_chart.value)
        _chart.value.removeInteraction(tclass)
})

defineExpose({
    data: _chart.value
})

</script>